﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class CompaniesByMaster : ClassManager.SessionManagerPage
    {
        private void GetAllCompaniesByMasterUsername(string MasterUsername)
        {
            GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.CompaniesByMasters> CompaniesByMastersEntities = GPSTrackingDBV2.Data.DataRepository.CompaniesByMastersProvider.GetByMasterUsername(MasterUsername);
            GPSTrackingDBV2.Data.DataRepository.CompaniesByMastersProvider.DeepLoad(CompaniesByMastersEntities, true, GPSTrackingDBV2.Data.DeepLoadType.IncludeChildren, typeof(GPSTrackingDBV2.Entities.Companies));

            CompanyGridLinks.DataSource = CompaniesByMastersEntities;
        }

        protected void Page_Load(object sender, EventArgs e)
        {    
            //uscCompanySearch.OnAcceptEvent += uscCompanySearch_OnAcceptEvent;
            if (!Page.IsPostBack)
            {
                GridSortExpression expression = new GridSortExpression();
                expression.FieldName = GPSTrackingDBV2.Entities.MastersColumn.MasterUsername.ToString();
                expression.SetSortOrder("Ascending");
                this.MastersGrid.MasterTableView.SortExpressions.AddSortExpression(expression);


                expression = new GridSortExpression();
                expression.FieldName = "CompanyIdSource.Name";
                expression.SetSortOrder("Ascending");
                this.CompanyGridLinks.MasterTableView.SortExpressions.AddSortExpression(expression);
            }
        }

        protected void uscCompanySearch_OnCancelEvent()
        {
            resizeGrid();
        }

        protected void uscCompanySearch_OnAcceptEvent(List<GridDataItem> rows)
        {
            string MasterUsername = getMasterIDSelected();//row.Cells[3].Text;
            
            foreach (GridDataItem row in rows)
            {
                try
                {
                    if (string.IsNullOrEmpty(MasterUsername))
                    {
                        resizeGrid();
                        showErrorMessage("Debe selecionar un Master para asociar las compañías.");
                        return;
                    }

                    int companyID = int.Parse(row.Cells[3].Text);
                    //Insert
                    GPSTrackingDBV2.Entities.CompaniesByMasters CompaniesByMastersEntity = new GPSTrackingDBV2.Entities.CompaniesByMasters();
                    CompaniesByMastersEntity.MasterUsername = MasterUsername;
                    CompaniesByMastersEntity.CompanyId = companyID;

                    GPSTrackingDBV2.Data.DataRepository.CompaniesByMastersProvider.Insert(CompaniesByMastersEntity);
                }
                catch{
                    //
                }
            }
            uscCompanySearch.getCompaniesToAssociate();
            GetAllCompaniesByMasterUsername(MasterUsername);
            CompanyGridLinks.DataBind();
            resizeGrid();
        }

        protected void CompanyGridLinks_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            try
            {
                string MasterUsername = getMasterIDSelected();        
                GPSTrackingDBV2.Entities.CompaniesByMasters CompaniesByMastersEntity = ClassManager.InvokeEntityManager.Invoke_CompaniesByMasters_Entity(e);
                CompaniesByMastersEntity.OriginalCompanyId = CompaniesByMastersEntity.CompanyId;
                CompaniesByMastersEntity.OriginalMasterUsername = CompaniesByMastersEntity.MasterUsername = MasterUsername;
                GPSTrackingDBV2.Data.DataRepository.CompaniesByMastersProvider.Delete(CompaniesByMastersEntity);

                //Refresh Data
                GetAllCompaniesByMasterUsername(CompaniesByMastersEntity.MasterUsername);
                CompanyGridLinks.DataBind();
                resizeGrid();
            }
            catch (Exception ex)
            {
                HiddenFieldError.Value = ClassManager.CustomExceptionManager.Generate_Error(ex.Message);            
                showErrorMessage("No se puede eliminar la companía porque esta asociado otros registros.");
            }


        }
        
        protected void lbClearMasterFilters_Click(object sender, EventArgs e)
        {
            MastersGrid.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in MastersGrid.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }

            setSessionManager(string.Empty);

            MastersGrid.MasterTableView.Rebind();
            clearCompanyGridLinks();
        }

        protected void lbClearCompaniesFilters_Click(object sender, EventArgs e)
        {
            CompanyGridLinks.MasterTableView.FilterExpression = string.Empty;

            foreach (GridColumn column in CompanyGridLinks.MasterTableView.RenderColumns)
            {
                if (column is GridBoundColumn)
                {
                    GridBoundColumn boundColumn = column as GridBoundColumn;
                    boundColumn.CurrentFilterValue = string.Empty;
                }
            }
            CompanyGridLinks.MasterTableView.Rebind();
        }

        public void showErrorMessage(string msg)
        {
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "objWindowsMessageManager.show_Error", "objWindowsMessageManager.show_Error('" + msg + "','Compañías por Master...');", true);
        }

        protected void CompanyGridLinks_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            string MasterUsername = getMasterIDSelected();
            GetAllCompaniesByMasterUsername(MasterUsername);
            resizeGrid();
        }

        private void resizeGrid(){
            float height = float.Parse(HiddenFieldHeight.Value.ToString()) - 25;
            CompanyGridLinks.Height = Unit.Parse((height / 2).ToString());
            MastersGrid.Height = Unit.Parse((height - (height / 2)).ToString());
        }

        protected void MastersGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            GetAllMasters();
            resizeGrid();
        }
        
        private void GetAllMasters()
        {
            MastersGrid.DataSource = GPSTrackingDBV2.Data.DataRepository.MastersProvider.GetAll();
        }

        protected string getMasterIDSelected()
        {

            try
            {
                foreach (Telerik.Web.UI.GridDataItem selectedItem in MastersGrid.SelectedItems)
                {
                    return selectedItem["MasterUsername"].Text;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return "";
        }

        protected void MastersGrid_SelectedIndexChanged(object sender, EventArgs e)
        {
            string MasterUsername = getMasterIDSelected();

            setSessionManager(MasterUsername);

            //Refresh Data
            GetAllCompaniesByMasterUsername(MasterUsername);
            CompanyGridLinks.DataBind();
            resizeGrid();
        }

        private void clearCompanyGridLinks()
        {
            CompanyGridLinks.DataSource = new string[] { };
            CompanyGridLinks.DataBind();
        }

        protected void MastersGrid_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == RadGrid.SortCommandName || e.CommandName == RadGrid.FilterCommandName)
            {
                clearCompanyGridLinks();
                setSessionManager(string.Empty);
            }
        }

        protected void setSessionManager(string value) {
            SessionManager objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];
            objSessionManager.CompaniesByMaster_companySearch_MasterUsername = value;
            HttpContext.Current.Session["SessionManager"] = objSessionManager;
        }

        protected SessionManager getSessionManager() {
            return (SessionManager)HttpContext.Current.Session["SessionManager"];
        }

        protected void lbShowError_Click(object sender, EventArgs e)
        {
            showErrorMessage(HiddenFieldError.Value);
        }

    }
}